package edu.hawaii.duedates.library;

import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;
import edu.hawaii.duedates.BorrowedItem;
import edu.hawaii.duedates.Lender;

/**
 * This class is built for actions related to the UH Manoa Library system. It is also implements the
 * Lender interface. Must have login and getInfo.
 * 
 * @author John Ly
 * @author John Zhou
 */

public class UhManoa implements Lender {

  /**
   * Attempts to login to UH Manoa Library system.
   * 
   * @param id The UH user ID.
   * @param lastName The UH user's last name.
   * @return The WebConversation instance after successful login.
   * @throws Exception If login was not successful with these credentials.
   */
  public WebConversation login(String id, String lastName) throws Exception {
    String url = "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=pbLogon";
    // UH Library website has bogus JavaScript code.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(url);
    WebResponse response = conversation.getResponse(request);
    WebForm form = response.getFormWithName("logonpage");
    form.setParameter("BC", id);
    form.setParameter("LN", lastName);
    form.submit();
    response = conversation.getCurrentPage();
    if (response.getText().contains("Sorry, Login unsuccessful")) {
      throw new Exception("Error while logging in to UH Library");
    }
    return conversation;
  }

  /**
   * Given a logged in user to the UH Library site, provides info about their library books.
   * 
   * @param id The UH user ID.
   * @param lastName The UH user's last name.
   * @param bookList The List to add the books to, contains books from other libraries.
   * @return The List with the newly added books.
   * @throws Exception If problems occur parsing the site pages.
   */
  public List<BorrowedItem> 
    getInfo (String id, String lastName, List<BorrowedItem> bookList) throws Exception {
    // String uhSiteNoItemString = "You have no items checked out.";
    WebConversation conversation = this.login(id, lastName);
    WebResponse response = conversation.getCurrentPage();

    int dueDateColumn = 3;
    int bookTitleColumn = 1;
    // Assume the "Checked Out Items" table contains "Renew"
    WebTable table = response.getTableStartingWith("Renew?");
    // If Renew column doesn't exist, then try "Item"
    if (table == null) {
      table = response.getTableStartingWith("Item");
      dueDateColumn = 2;
      bookTitleColumn = 0;
    }
    if (table != null) {
      String dueDate = "";
      String bookTitle = "";
      for (int i = 1; i < table.getRowCount(); i++) {
        dueDate = table.getCellAsText(i, dueDateColumn);
        bookTitle = table.getCellAsText(i, bookTitleColumn);
        Calendar cal = convertDateToCalendar(dueDate);
        BorrowedItem book = new BorrowedItem(bookTitle, cal, "Book", "UH Manoa");
        bookList.add(book);
      }
      return bookList;
    }
    return bookList;
  }
  
  /**
   * Converts the UH date string into Calendar object.
   * Example of the parameter: "Checked out: 10-27-08" 
   * @param uhdate The string which contains the date (mm-dd-yy) at the end.
   * @return The Calendar object created from the date given.
   */
  public Calendar convertDateToCalendar (String uhdate) {
    int monthPos = uhdate.length() - 8;
    int dayPos = uhdate.length() - 5;
    int yearPos = uhdate.length() - 2;
    int month = Integer.parseInt(uhdate.substring(monthPos, monthPos + 2));
    int day = Integer.parseInt(uhdate.substring(dayPos, dayPos + 2));
    int year = 2000 + Integer.parseInt(uhdate.substring(yearPos, yearPos + 2));
    Calendar cal = Calendar.getInstance(Locale.US);
    cal.set(Calendar.MONTH, month - 1);
    cal.set(Calendar.DAY_OF_MONTH, day);
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.HOUR_OF_DAY, 23);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.SECOND, 59);
    cal.set(Calendar.MILLISECOND, 0);
    return cal;
  }

}
